﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
namespace Gronia.WPF.Controls
{
    public partial class CameraPanel : Panel
    {
        protected override Size MeasureOverride(Size availableSize)
        {
            foreach (UIElement uielement in InternalChildren)
            {
                if (uielement != null)
                {
                    uielement.Measure(availableSize);
                }
            }
            return availableSize;
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            foreach (UIElement uielement in base.InternalChildren)
            {
                if (uielement != null)
                {
                    Point position = default(Point);
                    double x = GetX(uielement) - CameraX;
                    double y = GetY(uielement) - CameraY;
                    double z = GetZ(uielement);
                    if (z < CameraZ)
                    {
                        double scale;
                        if (ZScaleFactor > 0.0)
                        {
                            scale = ZScaleFactor / (ZScaleFactor + Math.Abs(CameraZ - z));
                        }
                        else
                        {
                            scale = 1.0;
                        }
                        position.X = finalSize.Width / 2.0 - uielement.DesiredSize.Width / 2.0 + x * scale;
                        position.Y = finalSize.Height / 2.0 - uielement.DesiredSize.Height / 2.0 - y * scale;
                        uielement.SetValue(ZIndexProperty, (int)z);
                        uielement.RenderTransformOrigin = new Point(0.5, 0.5); 
                        
                        if (uielement.RenderTransform != null && uielement.RenderTransform.Inverse != null)
                        {
                            SetScaleTransform(uielement, uielement.RenderTransform);
                        }

                        Matrix value = GetScaleTransform(uielement).Value;
                        value.M11 = scale;
                        value.M22 = scale;
                        uielement.RenderTransform = new MatrixTransform(value);
                        uielement.Arrange(new Rect(position, uielement.DesiredSize));
                        continue;
                    } 
                    if (uielement.RenderTransform != null && uielement.RenderTransform.Inverse != null)
                    {
                        SetScaleTransform(uielement, uielement.RenderTransform);
                    }
                    uielement.RenderTransform = new MatrixTransform(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
                }
            }
            return finalSize;
        }
    }
}